import React, { useState, useEffect } from 'react';
import axiosInstance from '../api/axiosInstance';
import { Table, TableBody, TableCell, TableHead, TableRow, Paper, Button } from '@mui/material';
import { useNavigate } from 'react-router-dom';

const RadiologistList = () => {
  const [radiologists, setRadiologists] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    fetchRadiologists();
  }, []);

  const fetchRadiologists = async () => {
    try {
      const response = await axiosInstance.get('api/radiologists/');
      setRadiologists(response.data);
    } catch (error) {
      console.error('Ошибка при загрузке списка врачей:', error);
    }
  };

  const handleEditClick = (radiologist) => {
    navigate(`/radiologists/edit/${radiologist.id}`);
  };

  const handleDeleteClick = async (radiologistId) => {
    try {
      await axiosInstance.delete(`api/radiologists/${radiologistId}/`);
      setRadiologists(radiologists.filter(r => r.id !== radiologistId));
    } catch (error) {
      console.error('Ошибка при удалении врача:', error);
    }
  };

  return (
    <Paper>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>Имя</TableCell>
            <TableCell>Фамилия</TableCell>
            <TableCell>Модальность</TableCell>
            <TableCell>Ставка</TableCell>
            <TableCell>Действия</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {radiologists.map((radiologist) => (
            <TableRow key={radiologist.id}>
              <TableCell>{radiologist.first_name}</TableCell>
              <TableCell>{radiologist.last_name}</TableCell>
              <TableCell>{radiologist.modality}</TableCell>
              <TableCell>{radiologist.rate}</TableCell>
              <TableCell>
                <Button
                  color="primary"
                  variant="contained"
                  onClick={() => handleEditClick(radiologist)}
                  style={{ marginRight: '8px' }}
                >
                  Редактировать
                </Button>
                <Button
                  color="secondary"
                  variant="contained"
                  onClick={() => handleDeleteClick(radiologist.id)}
                >
                  Удалить
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </Paper>
  );
}

export default RadiologistList;